<?php

namespace App\Models;

use Encore\Admin\Auth\Database\Role as BaseRole;
use Illuminate\Database\Eloquent\Model;
//use Encore\Admin\Traits\DefaultDatetimeFormat;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;

class NewRole extends Model
{
    //
    protected $table = 'yt_new_roles';


//    use DefaultDatetimeFormat;

    protected $fillable = [
        'name',
        'slug',
//        'path',
        'creator',
        'all_auth',// 是否：有全部的权限
    ];

    const Admin_slug = 'administrator';

    public function scopeNotAdmin($qry)
    {
        if (!NewUsers::isAdmin()) {
            $qry->where('slug','!=', self::Admin_slug);
        }
    }

    // 角色select列表
    static function roleSelect()
    {
       return self::query()->notAdmin()->orderBy('id')->pluck('name', 'id');
    }
    /*
        public function getHttpPathAttribute(): array
        {
    //        explode("\n", str_replace("\r\n", "\n", $path));
            $permissions = $this->permissions()->pluck('http_path')->toArray();
           return $permissions[0] ?? [];
        }

        public function setHttpPathAttribute($path)
        {
            $path[] = '/';
            $path[] = '/auth/setting';
            $this->permissions()->update([
                'http_path' =>  implode("\r\n", array_filter($path))
            ]);
        }*/

    public function menus()
    {
        $pivotTable = config('admin.database.role_menu_table');
//        $pivotTable = 'yt_new_role_menu';
//        $relatedModel = config('admin.database.menu_model');

        return $this->belongsToMany(NewMenu::class, $pivotTable, 'role_id', 'menu_id');
    }



    public function users()
    {
        $pivotTable = config('admin.database.role_users_table');
        return $this->belongsToMany(NewUsers::class, $pivotTable, 'role_id', 'user_id');
    }


    // 删除角色所有用户菜单的缓存
    static function clearUserMenuCache(self $role)
    {
        $usersId = $role->users->pluck('id')->toArray();
        if (count($usersId)) {
            foreach($usersId as $id) {
//                Cache::forget(config('constants.User_menu_key').$id);
                delUserMenuCache($id);
            }
        }
    }

//    public function parent()
//    {
//        return $this->belongsTo(static::class, 'parent_id');
//    }

    //角色映射用户数
   /* public static function roleUsers(){
        $pivotTable = config('admin.database.role_users_table');
        $roleUsers = DB::table($pivotTable)
            ->selectRaw('role_id,count(*) as user_ids')
            ->groupBy('role_id')
            ->pluck('user_ids', 'role_id')
            ->toArray();

        return $roleUsers;
    }*/

}
